/**
 * Recurses directory and returns .js files
 *  - ensures that subdirs(and files) are appended to array
 *  - you have to ensure your root directory contains an app.js that gets loaded at the start
 */

var sys = require ('sys'), fs = require ('fs'), seen_files = [];

function watchDir(dir,cb) {
	if (isDir(dir)) { 
		readDir(dir).forEach(function(file) {
			fs.unwatchFile(file);
		});
		readDir(dir).forEach(function(file) {
			_watchFile(file,cb);
		});
	}
}
function onlyPrintIfNew(file) {
	var seen = false;
	seen_files.forEach(function(f) {
		if (f === file) { seen = true; }
	});
	if (!seen) {
		sys.puts(file);
		seen_files.push(file);
	}
}

function _watchFile(file,cb) {
	onlyPrintIfNew(file);
	fs.watchFile(file, function (curr, prev) {
		fs.readFile(file, function(err,data) {
			if (data) { 
				cb.call(this,file,data);
			}
		});
	});
}

// reads a directory recursively into an array of files
function readDir(dir) {
	var files = [], dirs = [], tmp = [];
	dir = dir.replace(/\/$/,'');
	tmp = fs.readdirSync(dir).sort();
	tmp.forEach(function(f) {
		var path = dir + "/" + f;
		if (/(js|css|html|json)$/.test(path)) { 
			files.push(path); 
		}

		if (isDir(path)) { dirs.push(path); } 
	});
	dirs.forEach(function(d) { files = files.concat(readDir(d)); });
	return files;
}


function isDir(path) {
	if (fs.statSync(path).isDirectory())  { return true; }
	return false;
}
exports.watchDir = watchDir;
